import { packParams, isEmptyObject } from "../utils";
import PromiseAggregation from "./promise-aggregation";
import { isBrandApp, isIos } from "../utils/checkEnv";
import axios from "axios";
import { GOODS_ERROR_MSG } from '../constants';

//定义直播前缀
var alivePrefix = ""
// if (window && window.isAlive){
// }
alivePrefix = '/_alive'

console.log('alivePrefix',alivePrefix);

axios.interceptors.response.use(
  function (res) {
    return res.data;
  },
  function (error) {
    return Promise.reject(error);
  }
);

export function fetchNecessaryInfo(
  defaultData,
  spuId,
  skuId,
  addressId
) {
  async function doFetch() {
    //如果store里有数据，则不再请求接口
    const {
      shopConf,
      businessConf: featureInfo,
      marketingData,
      superVipInfo,
    } = defaultData || {};
    const aggregation = new PromiseAggregation();
    aggregation
      .append(
        "shopConf",
        isEmptyObject(shopConf) ? fetchShopConf() : Promise.resolve(shopConf)
      )
      .append(
        "featureInfo",
        isEmptyObject(featureInfo)
          ? fetchFeatureInfo(spuId)
          : Promise.resolve(featureInfo)
      )
      .append("goodsPackage", fetchGoodsPackage(spuId));
    // .append("cartInfo", fetchCartInfo());

    const spuInfo = await fetchGoodsSpuInfo(spuId);
    // 商品不存在、已删除
    if (!spuInfo) {
      return Promise.reject({
        res: {
          response: {
            msg: GOODS_ERROR_MSG
          },
        },
      });
    }
    const { resource_type, spu_type, resource_id } = spuInfo;
    const scenes = 'buy_page'
    const hasActivityInfo =
      marketingData && marketingData.marketing_info?.activity_id;

    aggregation
      .append(
        "confirmDetail",
        fetchConfirmDetail(spuId, spu_type, resource_type, skuId, addressId)
      )
      .append(
        "activityInfo",
        hasActivityInfo
          ? Promise.resolve(marketingData)
          : fetchActivityInfo(spuId, spu_type, resource_type)
      )
      .append(
        "svipInfo",
        isEmptyObject(superVipInfo)
          ? fetchVipInfo(resource_id, resource_type)
          : Promise.resolve(superVipInfo)
      ).append(
        "assertNeedCollectInfo",
        fetchCollectInfo(resource_type, resource_id, scenes)
      );
    if (isBrandApp && isIos) {
      aggregation
        .append(
          "isSupportCoin",
          fetchCoinSupport({ resource_id, resource_type })
        )
        .append(
          "coinInfo",
          fetchCoinBalance({
            user_id: window.USERID,
            app_id: window.APPID,
            wallet_type: 1,
          })
        );
    }

    //获取自提开启状态
    aggregation.append("userCanPick", fetchPickState({spu_id:spuId}));

    return aggregation.aggregate();
  }

  return doFetch();
}

export function fetchShopConf() {
  return fetchInfo(
    "/shop_conf/get_shop_module_conf",
    packParams({
      modules: ["switches", "guideContact", "physicalGoods"],
    })
  );
}

function fetchGoodsSpuInfo(spuId) {
  return fetchInfo(
    "/xe.ecommerce.goods_center.get_spu_info/1.0.0",
    packParams({ spu_id: spuId })
  );
}
export function fetchConfirmDetail(spuId, spuType, resourceType, skuId, address_id) {
  return fetchInfo(
    `${alivePrefix}/xe.transaction.order.confirm_detail.get/1.0.0`,
    packParams({
      spu_id: spuId,
      resource_type: resourceType,
      spu_type: spuType,
      sku_id: skuId || "",
      address_id,
    })
  );
}
function fetchFeatureInfo(spuId) {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.goods_center.get_feature_info_detail/1.0.0`,
    packParams({
      spu_id: spuId,
    })
  );
}
//获取营销信息
function fetchActivityInfo(spuId, spuType, resourceType) {
  return fetchInfo(
    `${alivePrefix}/xe.marketing.basic.activity.info/1.0.0`,
    packParams({
      spu_id: spuId,
      spu_type: spuType,
      resource_type: resourceType,
    })
  );
}

export function fetchCollectInfo (resourceType, resourceId, scenes) {
  return fetchInfo(
    `/xe.info_collect.assert_need_collect_gray/1.0.0`,
    packParams({
      resource_type: resourceType,
      resource_id: resourceId,
      scenes,
      user_id: window.USERID,
      app_id: window.APPID
    })
  );
}

function fetchVipInfo(resourceId, resourceType) {
  return fetchInfo(
    `${alivePrefix}/xe.svip.info.get_by_resource.detail/1.0.0`,
    packParams({
      resource_id: resourceId,
      resource_type: resourceType,
    })
  );
}

// 商品的套餐信息
function fetchGoodsPackage(spu_id) {
  return fetchInfo(
    `/xe.ecommerce.goods_center.get_package_detail/1.0.0`,
    packParams({
      spu_id,
    })
  );
}

// 初始化购物车信息
export function fetchCartInfo(params) {
  return fetchInfo(
    `${alivePrefix}/xe.transaction.user_cart.list.get/1.0.0`,
    packParams(params)
  );
}
//获取支付方式列表
export function fetchPayWay(params) {
  return fetchInfo(
    `${alivePrefix}/xe.transaction.ogw.order.pay.config_list/1.0.0`,
    {
      bizData: params
    },
    'post',
    {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  );
}

// 获取收货地址
export function getAddressList() {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.entity_goods.receive_address.list/1.0.0`,
    packParams({})
  );
}

// 创建地址
export function createAddress(params) {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.entity_goods.receive_address.add/1.0.0`,
    packParams(params)
  );
}

// 编辑时获取地址详情回填
export function getGoodsAddressDetail(params) {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.entity_goods.receive_address.detail/1.0.0`,
    packParams(params)
  );
}

// 获取收货地址省市区
export function getGoodsRegion() {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.entity_goods.get_goods_region/1.0.0`,
    packParams({})
  );
}

// 填充手机号
export function obtainPhone() {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.user_service.get_user_info/1.0.0`,
    packParams({ field_list: ["phone"] })
  );
}

// 新建地址
export function addressAdd(params) {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.entity_goods.receive_address.add/1.0.0`,
    packParams(params)
  );
}

// 修改地址
export function addressEdit(params) {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.entity_goods.receive_address.edit/1.0.0`,
    packParams(params)
  );
}

// 删除地址
export function addressDelete(params) {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.entity_goods.receive_address.del/1.0.0`,
    packParams(params)
  );
}

// 初始化自提人信息
export function getPickerInfo(params = {}) {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.logistics_go.get_picker_info/1.0.0`,
    packParams(params)
  );
}

// 自提人列表
export function getPickerList() {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.logistics_go.get_picker_list/1.0.0`,
    packParams({})
  );
}

// 自提点列表
export function getDeliveryPlaceList(params) {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.logistics_go.get_self_delivery_place_list/1.0.0`,
    packParams(params)
  );
}

// 编辑提货人信息
export function updatePicker(params) {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.logistics_go.update_picker/1.0.0`,
    packParams(params)
  );
}

// 删除提货人信息
export function deletePicker(params) {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.logistics_go.del_picker/1.0.0`,
    packParams(params)
  );
}

// 新增提货人
export function addPicker(params) {
  return fetchInfo(
    `${alivePrefix}/xe.ecommerce.logistics_go.add_picker/1.0.0`,
    packParams(params)
  );
}
export function jumpLoginUrl(params) {
  return fetchInfo(
    `${alivePrefix}/xe.account-platform.account.get_login_url`,
    packParams(params)
  );
}

function fetchInfo(url, params, method = "post", headers) {
  let promise;
  if (['post', 'put', 'patch'].includes(method.toLocaleLowerCase())) {
    promise = axios[method](url, params, { headers });
  } else {
    promise = axios[method](url, {
      params,
      headers
    })
  }
  return promise.then((res) => {
    return res.code === 0 ? res.data : Promise.reject(res);
  })
    .catch((err) => {
      return Promise.reject({
        req: {
          url,
          method,
          params,
        },
        res: {
          response: err,
        },
      });
    });
}

/**
 * 获取虚拟币余额
 * @param {Object} params
 * @returns
 */
export function fetchCoinBalance(params) {
  return fetchInfo(
    `${alivePrefix}/xe.transaction.get.virtual.balance.user/1.0.0`,
    packParams(params)
  );
}

/**
 * 获取虚拟币是否支持
 * @param {Object} params
 * @returns promise
 */
export function fetchCoinSupport(params) {
  return fetchInfo(
    `${alivePrefix}/xe.transaction.ios.coin/can_use/1.0.0`,
    packParams(params)
  ).then((data) => Boolean(data.is_ios_coin));
}

//判断是否在下单2.0灰度名单里，是则最新下单页面；否则走老的下单页
export const isInOrderGray = () => {
  return axios.post(`${alivePrefix}/xe.transaction.ogw.create_order_grayscale_control/1.0.0`, {}, {
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    },
    timeout: 3000
  }).then((res) => {
    if (res?.data?.is_gray) {
      return true;
    }
    return Promise.reject(res);
  });
}

// 获取B端填写手机号配置
export const getBindPhoneConfig = () => {
  return fetchInfo("/user/shop_phone_bind_conf", packParams({}));
};

// 获取自提是否开启
function fetchPickState(params) {
  return axios.post(`${alivePrefix}/xe.ecommerce.logistics_go.get_self_pick_state/1.0.0`, packParams(params)).then(
    (res) => {
      if (res) {
        return res.data?.self_service_switch === 1;
      } else {
        // return Promise.reject(res);
        //todo 这个接口经常失败
        return false;
      }
    }
  );
}

// 获取默认地址（购物车场景下）
export const getDefaultAddressInfo = () => {
  return fetchInfo(`${alivePrefix}/xe.order.address.info/1.0.0`, packParams({}));
};


export const checkOLCDuplicateOrder = data => {
  return fetchInfo(`${alivePrefix}/faceTeach/check_student_class`, packParams(data));
}

// 商品的套餐信息
export const getGoodsPackage = (params) => {
  return fetchInfo(`/xe.ecommerce.goods_center.get_package_detail/1.0.0`, packParams(params));
};

export const getGoodsInfo = (params) => {
  return fetchInfo(`${alivePrefix}/xe.ecommerce.entity_goods.goods_package.get_goods_list/1.0.0`, packParams(params));
};

// 获取小程序SDK支付设置
export const getMiniprogramSdkPaySetting = () => {
  return fetchInfo(`/xe.sdk.config.mp_payment_config.get/1.0.0`, packParams({}), 'get')
}

// 判断商品是在支付前还是支付后签署电子合同
export const getContractInfo = (params) => {
  return fetchInfo(`${alivePrefix}/xe.transaction.contract_resource.info/1.0.0`, packParams(params))
}

// 查询订单签署任务链接
export const getSignUrl = (params) => {
  return fetchInfo(`${alivePrefix}/xe.transaction.contract.get_sign_url/1.0.0`, packParams(params))
}

// 灰度接口
export const getGray = (params) => {
  return fetchInfo(`${alivePrefix}/xe.transaction.ogw.create_order_grayscale_control/1.0.0`, packParams(params))
}
